#include "product_model.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QColor>

ProductModel::ProductModel(QObject *parent) : QSqlQueryModel(parent) {
    refresh();
}

QVariant ProductModel::data(const QModelIndex &index, int role) const {
    if (!index.isValid())
        return QVariant();
    
    // 库存预警颜色显示
    if (role == Qt::BackgroundRole) {
        int stockColumn = 5; // 库存数量列
        int minStockColumn = 6; // 最低库存列
        
        if (index.column() == stockColumn) {
            int stock = QSqlQueryModel::data(index).toInt();
            int minStock = QSqlQueryModel::data(this->index(index.row(), minStockColumn)).toInt();
            
            if (stock <= 0) {
                return QColor(255, 200, 200); // 红色背景，库存为0
            } else if (stock < minStock) {
                return QColor(255, 255, 200); // 黄色背景，库存不足
            }
        }
    }
    
    // 金额列右对齐
    if (role == Qt::TextAlignmentRole) {
        if (index.column() == Price || index.column() == Cost) {
            // 使用 QVariant::fromValue 来正确转换对齐标志
            return QVariant::fromValue(Qt::AlignRight | Qt::AlignVCenter);
        }
        // 其他列默认左对齐
        return QVariant::fromValue(Qt::AlignLeft | Qt::AlignVCenter);
    }
    
    return QSqlQueryModel::data(index, role);
}

QVariant ProductModel::headerData(int section, Qt::Orientation orientation, int role) const {
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case Id: return "ID";
        case Name: return "产品名称";
        case Barcode: return "条形码";
        case Price: return "售价";
        case Cost: return "成本";
        case Stock: return "库存";
        case MinStock: return "最低库存";
        case Category: return "分类";
        case Supplier: return "供应商";
        default: return QVariant();
        }
    }
    return QSqlQueryModel::headerData(section, orientation, role);
}

void ProductModel::refresh() {
    QString queryStr = "SELECT id, name, barcode, price, cost, stock_quantity, "
                       "min_stock, category, supplier "
                       "FROM products";
    if (!currentFilter.isEmpty()) {
        queryStr += " WHERE " + currentFilter;
    }

    queryStr += " ORDER BY id DESC";

    setQuery(queryStr);
}

bool ProductModel::addProduct(const Product &product) {
    QSqlQuery query;
    query.prepare("INSERT INTO products (name, barcode, price, cost, "
                 "stock_quantity, min_stock, category, supplier, description) "
                 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    query.addBindValue(product.name);
    query.addBindValue(product.barcode);
    query.addBindValue(product.price);
    query.addBindValue(product.cost);
    query.addBindValue(product.stockQuantity);
    query.addBindValue(product.minStock);
    query.addBindValue(product.category);
    query.addBindValue(product.supplier);
    query.addBindValue(product.description);
    
    if (query.exec()) {
        refresh();
        return true;
    }
    return false;
}

bool ProductModel::updateProduct(const Product &product) {
    QSqlQuery query;
    query.prepare("UPDATE products SET name = ?, barcode = ?, price = ?, "
                 "cost = ?, min_stock = ?, category = ?, supplier = ?, "
                 "description = ?, updated_time = CURRENT_TIMESTAMP "
                 "WHERE id = ?");
    
    query.addBindValue(product.name);
    query.addBindValue(product.barcode);
    query.addBindValue(product.price);
    query.addBindValue(product.cost);
    query.addBindValue(product.minStock);
    query.addBindValue(product.category);
    query.addBindValue(product.supplier);
    query.addBindValue(product.description);
    query.addBindValue(product.id);
    
    if (query.exec()) {
        refresh();
        return true;
    }
    return false;
}

bool ProductModel::deleteProduct(int productId) {
    QSqlQuery query;
    query.prepare("DELETE FROM products WHERE id = ?");
    query.addBindValue(productId);
    
    if (query.exec()) {
        refresh();
        return true;
    }
    return false;
}

Product ProductModel::getProductById(int productId) {
    Product product;
    QSqlQuery query;
    query.prepare("SELECT id, name, barcode, price, cost, stock_quantity, "
                 "min_stock, category, supplier, description "
                 "FROM products WHERE id = ?");
    query.addBindValue(productId);
    
    if (query.exec() && query.next()) {
        product.id = query.value(0).toInt();
        product.name = query.value(1).toString();
        product.barcode = query.value(2).toString();
        product.price = query.value(3).toDouble();
        product.cost = query.value(4).toDouble();
        product.stockQuantity = query.value(5).toInt();
        product.minStock = query.value(6).toInt();
        product.category = query.value(7).toString();
        product.supplier = query.value(8).toString();
        product.description = query.value(9).toString();
    }
    
    return product;
}

void ProductModel::setFilter(const QString &filter)
{
    currentFilter = filter;
    refresh();
}
